package com.etc.patient.service.impl;

import cn.hutool.json.JSONUtil;
import com.etc.common.entity.MedicalRecord;
import com.etc.common.utils.Result;
import com.etc.patient.mapper.MedicalRecordMapper;
import com.etc.patient.service.MedicalRecordService;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import java.util.ArrayList;
import java.util.List;

import static com.etc.common.utils.RedisConstants.CACHE_MEDICALRECORD;

/**
 * @author 29322
 */
@Service
public class MedicalRecordServiceImpl implements MedicalRecordService {
    @Resource
    private MedicalRecordMapper mrMapper;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result queryByDocId(Integer pageNum, Integer pageSize, String docId) {
        //判断缓存中是否存在
        Boolean isExist = stringRedisTemplate.hasKey(CACHE_MEDICALRECORD + ":docId:" + docId);
        if (!isExist) {
            List<MedicalRecord> list = mrMapper.queryByDocId(docId);
            for (MedicalRecord medicalRecord : list) {
                stringRedisTemplate.opsForList().rightPush(CACHE_MEDICALRECORD + ":docId:" + docId, JSONUtil.toJsonStr(medicalRecord));
            }
        }
        //存在
        List<String> json = stringRedisTemplate.opsForList().range(CACHE_MEDICALRECORD + ":docId:" + docId,
                pageSize * (pageNum - 1), pageSize * (pageNum - 1) + pageSize - 1);
        List<MedicalRecord> list = JSONUtil.toList(json.toString(), MedicalRecord.class);
        return Result.ok(list, (long) list.size());
    }

    @Override
    public Result queryByDocIdLike(Integer pageNum, Integer pageSize, String docId, String like) {
        List<MedicalRecord> result = mrMapper.queryByDocIdLike(docId, like, pageSize * (pageNum - 1), pageSize);
//        List<String> list = stringRedisTemplate.opsForList().range(CACHE_MEDICALRECORD + ":docId:" + docId,
//                pageSize * (pageNum - 1), pageSize * (pageNum - 1) + pageSize - 1);
//        List<MedicalRecord> medicalRecordList = JSONUtil.toList(list.toString(), MedicalRecord.class);
//        List<MedicalRecord> result = new ArrayList<>();
//        for (MedicalRecord medicalRecord : medicalRecordList) {
//            String patientName = medicalRecord.getPatientName();
//            if (patientName.indexOf(like) >= 0) {
//                result.add(medicalRecord);
//            }
//        }
        return Result.ok(result, (long) result.size());
    }
}
